package com.ztools.pc.service.impl.listener;

import cn.hutool.core.util.StrUtil;
import com.ztools.common.util.common.Result;
import com.ztools.pc.service.listener.HomeService;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: seeTools
 * @Date: 2023/5/20  18:00
 * @Version 1.0
 */
@Service
public class HomeServiceImpl implements HomeService {

    @Resource
    private RedisTemplate redisTemplate;


    /**
     * redis监控
     *
     * @return Result
     */
    @Override
    public Result getCacheInfo() {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StrUtil.removeAll(key, "cmdstat_"));
            data.put("value", StrUtil.subBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return Result.success().data(result);
    }
}
